<template>
  <div class="chart"></div>
</template>

<script>
import * as echarts from "echarts";

export default {
  props: {
    highCharts: {
      type: Boolean,
      default: false,
    },
    init: {
      type: Function,
    },
    dataList: {
      type: Array,
      default: () => [],
    },
    options: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      chart: null,
      width: null,
    };
  },
  created() {},
  watch: {
    options: {
      deep: true,
      handler() {
        this.updateChartView();
      },
    },
    "$store.state.sidebarFold": function (newVal, oldVal) {
      // console.log("变化了", newVal, oldVal);
      this.timer = setTimeout(() => {
        this.updateChartView();
      }, 300);
    },
  },
  mounted() {
    if (this.highCharts) {
      this.$watch("dataList", {
        deep: true,
        handler() {
          this.init(this.dataList, highcharts, this.$el);
        },
      });
      this.init(this.dataList, highcharts, this.$el);
    } else {
      this.chart = echarts.init(this.$el);
    }
    this.updateChartView();
    window.addEventListener("resize", this.handleWindowResize);
    // this.addChartResizeListener()
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.handleWindowResize);
  },
  methods: {
    /**
     *对chart元素尺寸进行监听，当发生变化时同步更新echart视图
     */
    // addChartResizeListener () {
    //   const instance = ResizeListener({
    //     strategy: 'scroll',
    //     callOnAdd: true
    //   })

    //   instance.listenTo(this.$el, () => {
    //     if (!this.chart) return
    //     this.chart.resize()
    //   })
    // },

    /**
     *更新echart视图
     */
    updateChartView() {
      if (!this.chart || this.highCharts) return;
      this.handleWindowResize();
      this.chart.setOption(this.options, true);
    },

    /**
     *当窗口缩放时，echart动态调整自身大小
     */
    handleWindowResize() {
      if (!this.chart) return;
      if (this.highCharts) {
        this.chart.reflow();
      } else {
        // this.chart.resize();
        this.initEcharts();
      }
    },

    initEcharts() {
      this.$nextTick(() => {
        let _width = this.$el?.clientWidth;
        // console.log("_width", _width);
        // console.log(this.$el.parentNode.clientWidth);
        if (_width) {
          this.chart.resize({
            width: _width,
          });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.chart {
  width: 100%;
  height: 100%;
  background: transparent;
  z-index: 2;
}
</style>
